package cn.itsource.ymcc.service.impl;

import cn.itsource.util.AssertUtil;
import cn.itsource.ymcc.domain.AlipayInfo;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.dto.CourseOrderPayparamDto;
import cn.itsource.ymcc.dto.Order2PayParamDto;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import cn.itsource.ymcc.service.IAlipayInfoService;
import cn.itsource.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Cherish
 * @since 2022-08-19
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IAlipayInfoService alipayInfoService;

    /**
     * 不要主动报错，报错即签收消息失败，下次还会推送给你
     * @param order2PayParamDto
     */
    @Override
    @Transactional
    public void savePayOrder(Order2PayParamDto order2PayParamDto) {
        String orderNo = order2PayParamDto.getOrderNo();
        //消费消息一定要幂等
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        PayOrder payOrder = selectOne(wrapper);
        if(payOrder == null){
            payOrder = new PayOrder();
            BeanUtils.copyProperties(order2PayParamDto,payOrder);
            payOrder.setCreateTime(new Date());
            payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
            insert(payOrder);
        }
        // AssertUtil.isNull(payOrder,"支付单已经存在");//签收消息  这里不能报错，报错代表签收失败，下次还要消费
    }

    @Override
    public PayOrder checkPayOrder(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

    /**
     * 1.参数校验
     * 2.业务校验
     *  2.1 支付单不存在
     *  2.2 支付单状态不是待支付
     * 调用支付宝支付
     * 响应支付宝调用结果（就是from表单）
     *
     * @param dto
     * @return
     */
    @Override
    public String apply(CourseOrderPayparamDto dto) {
        //1.参数校验 JSR303
        //2.业务校验
        PayOrder payOrder = checkPayOrder(dto.getOrderNo());
        // 2.1 支付单不存在
        AssertUtil.isNotNull(payOrder,"支付单不存在！！");
        // 2.2 支付单状态不是待支付
        boolean isWaitPay = payOrder.getPayStatus() == PayOrder.STATE_WAIT_PAY;
        AssertUtil.isTrue(isWaitPay,"支付单状态非法！！");
        //调用对应的支付方式
        int payType = payOrder.getPayType().intValue();
        if(payType == 1){
            //调用支付宝支付
            return alipay(payOrder,dto);
        }else if(payType == 2){//微信

        }

        //响应对应的支付方式调用结果（就是from表单）
        return null;
    }

    @Override
    @Transactional
    public void cancelPayOrderByPayTimeOut(String orderNo) {
        PayOrder payOrder = checkPayOrder(orderNo);
        if(payOrder == null){
            return;
        }
        if(payOrder.getPayStatus() != PayOrder.STATE_WAIT_PAY){
            return;
        }
        //1.取消支付单
        payOrder.setPayStatus(PayOrder.STATE_CANCEL);
        payOrder.setUpdateTime(new Date());
        updateById(payOrder);
        //2.调用支付宝关闭交易
        try {
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderNo);
            log.info("调用支付宝关闭交易：{}", JSON.toJSONString(close));
            //2.1 关闭成功
            //2.2 关闭失败 notify的时候走退款
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String alipay(PayOrder payOrder, CourseOrderPayparamDto dto) {
        // 1. 设置参数（全局只需设置一次）
        AlipayInfo alipayInfo = alipayInfoService.selectList(null).get(0);
        Factory.setOptions(getOptions(alipayInfo));
        try {
            // 2.网页支付
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(
                    payOrder.getSubject(),
                    payOrder.getOrderNo(),
                    payOrder.getAmount().toString(),
                    //如果前端给我传递了同步回调地址，我就使用前端的，否则给默认页面
                    StringUtils.isEmpty(dto.getCallUrl()) ? alipayInfo.getReturnUrl():dto.getCallUrl()
            );
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println(response.getBody());
                return response.getBody();
            } else {
                System.err.println("调用失败，原因：" + response);
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }


    private Config getOptions(AlipayInfo alipayInfo) {
        Config config = new Config();
        config.protocol = alipayInfo.getProtocol();
        config.gatewayHost = alipayInfo.getGatewayHost();
        config.signType = alipayInfo.getSignType();
        config.appId = alipayInfo.getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = alipayInfo.getMerchantPrivateKey();
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = alipayInfo.getAlipayPublicKey();
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = alipayInfo.getNotifyUrl();
        return config;
    }
}
